import { _decorator, AssetManager, Color, Component, instantiate, Node, Prefab } from 'cc';
import { ChannelManager } from '../../Channel/ChannelManager';
const { ccclass, property } = _decorator;

@ccclass('ViewLoaderBase')
export abstract class ViewLoaderBase extends Component {
    /** Bundle资源 */
    public Bundle: AssetManager.Bundle = null;

    @property({ type: Boolean, displayName: "是否释放资源", tooltip: "是否在节点销毁时释放Bundle资源" })
    public isRelease: boolean = false;

    protected onDestroy(): void {
        // 释放Bundle资源
        if (this.isRelease && !this.Bundle) {
            this.releaseBundle();
        }
    }

    /**
     * 加载视图
     * @param bundleName 资源包名
     * @param viewPath 视图地址
     * @param onComplete 包加载完成回调
     * @param Bundle 默认包
     */
    protected LoadView(bundleName: string, viewPath: string, onComplete: Function) {
        ChannelManager.GetInstance().ShowLoading();
        let Bundle = AssetManager.instance.getBundle(bundleName);
        if (!this.Bundle) this.Bundle = Bundle;
        if (!this.Bundle) {
            AssetManager.instance.loadBundle(bundleName, (err, bundle: AssetManager.Bundle) => {
                if (!err) {
                    this.Bundle = bundle;
                    onComplete?.apply(bundle);
                    this.LoadView(bundleName, viewPath, null);
                } else {
                    console.error(`加载资源包失败!`, err);
                    ChannelManager.GetInstance().HideLoading();
                    ChannelManager.GetInstance().ShowNotice(`资源包加载错误!`, null, Color.RED);
                }
            })
        } else {
            onComplete?.apply(this.Bundle);
            this.Bundle.load(viewPath, Prefab, (err, prefab: Prefab) => {
                if (!err) {
                    let view: Node = instantiate(prefab);
                    view.setParent(this.node);
                    view.setPosition(0, 0);
                } else {
                    console.error(`加载视图失败!`, err);
                    ChannelManager.GetInstance().ShowNotice(`视图加载错误!`, null, Color.RED);
                }
                ChannelManager.GetInstance().HideLoading();
            });
        }
    }

    /**释放Bundle资源 */
    protected releaseBundle(): void {
        if (this.releaseBundle && !!this.Bundle) {
            this.Bundle.releaseAll();
            this.Bundle = null;
        }
    };
}